import React, {Component} from 'react';
import './Tabs.css';

// import {Link} from "react-router-dom";


class Tabs extends Component {
	constructor(props) {
		super(props);

		// console.log(props);

		this.state = {
			style: {
				left: 0,
				// width: 0
			},
			selectedIndex: props.meta.index
		}

	}

	// 点击tab
	clickTab(e) {
		this.changeTab.call(this, e);
		setTimeout(() => {
			this.changeRoute.call(this, e)
		}, 200);
	}

	// 切换路由
	changeRoute(e) {
		let tab = JSON.parse(e.target.dataset.tab);
		// console.log(tab);
		this.props.history.replace(tab.path);
	}

	// 切换tab
	changeTab(e) {
		// let tab = JSON.parse(e.target.dataset.tab);
		// let index = tab.index;

		// 获取点击元素的位置坐标
		let offsetX = e.target.offsetLeft;
		let offsetW = e.target.offsetWidth;
		// 更改样式
		this.setState(state => {
			return {
				style: {
					left: offsetX + 'px',
					width: offsetW + 'px',
					transition: '0.2s'
				},
				selectedIndex: this.props.meta.index
			}
		})
	}

	componentDidMount() {
		// console.log(1);
		// let firstTab = document.getElementsByClassName('tab')[this.props.meta.index];
		// console.log(firstTab);
		// console.log(this.selectedTab);

		let offsetX = this.selectedTab.offsetLeft;
		let offsetW = this.selectedTab.offsetWidth;

		this.setState(state => {
			return {
				style: {
					left: offsetX + 'px',
					width: offsetW + 'px',
				}
			}
		})
	}

	render() {
		return (
			<div className="tabs">
				{
					this.props.tabs.map((tab, index) => {
						return (
							// <div className={this.state.selectedIndex == index ? 'tab selected' : 'tab'} key={index} data-index={index} onClick={this.changeTab}>{tab}</div>
							<div ref={this.props.meta.index === index ? ref => this.selectedTab = ref : null}
								className={this.state.selectedIndex === index ? 'tab selected' : 'tab'} key={tab.path}
								data-tab={JSON.stringify(tab)} onClick={this.clickTab.bind(this)}>{tab.channel}</div>
						)
					})
				}
				<div className="underLine" style={this.state.style}/>
			</div>
		)
	}
}

export default Tabs;